//  this library.
import 'package:flutter/material.dart';
import 'package:hktk_app/dao/course_dao.dart';
import 'package:hktk_app/dao/login_dao.dart';
import 'package:hktk_app/dao/subject_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/subject/collection_type_enum.dart';
import 'package:hktk_app/model/course/note_video_model.dart';
import 'package:hktk_app/model/practice/practice_question_model.dart';
import 'package:hktk_app/model/subject/note_model.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/my_util.dart';

import 'package:hktk_app/util/sz_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';

/// 添加笔记组件
class NoteAddWidget extends StatefulWidget {
  /// 提交状态，true：试题提交，false：视频提交。
  final bool addType;

  /// 关联id，试题上传：章节/试卷id，视频上传：章节id
  final String relationId;

  /// 关联名称，试题上传：章节/试卷名，视频上传：章节名
  final String relationName;

  /// 试题id，试题上传笔记需要，默认为""
  final String qId;

  /// 题干冗余，试题上传笔记需要，默认为null
  final List<Stem>? stem;

  /// 类型，试题上传笔记需要，默认为chapter(章节)
  final CollectionTypeEnum type;

  /// 视频id，视频上传笔记需要，默认为”“
  final String videoId;

  const NoteAddWidget({
    super.key,
    required this.addType,
    required this.relationId,
    required this.relationName,
    this.qId = "",
    this.stem,
    this.type = CollectionTypeEnum.chapter,
    this.videoId = "",
  });

  /// 创建试题笔记提交组件
  const NoteAddWidget.question({
    super.key,
    required this.relationId,
    required this.relationName,
    required this.qId,
    required this.stem,
    required this.type,
  })  : addType = true,
        videoId = "";

  /// 创建视频笔记提交组件
  const NoteAddWidget.video({
    super.key,
    required this.relationId,
    required this.relationName,
    required this.videoId,
  })  : addType = false,
        qId = "",
        stem = null,
        type = CollectionTypeEnum.chapter;

  @override
  State<NoteAddWidget> createState() => _NoteAddWidgetState();
}

class _NoteAddWidgetState extends State<NoteAddWidget> {
  late BuildContext _context;

  /// 输入框控制器
  late TextEditingController _textController;

  /// 输入框焦点控制器
  late FocusNode _textFocusNode;

  /// 是否公布
  late bool _open;

  @override
  void initState() {
    super.initState();
    debugPrint("nodeAddWidget 组件 -> initState 方法执行 ===> ");
    debugPrint("");
    _textController = TextEditingController();
    _textFocusNode = FocusNode();
    _open = true;
  }

  @override
  void dispose() {
    super.dispose();
    debugPrint("nodeAddWidget 组件 -> dispose 方法执行 ===> ");
    debugPrint("");
    _textController.dispose();
    _textFocusNode.dispose();
    ToastUtil.loadingBoxRemove();
  }

  @override
  Widget build(BuildContext context) {
    debugPrint("nodeAddWidget 组件 -> build 方法执行 ===> ");
    debugPrint("");
    _context = context;
    return Container(
      padding: EdgeInsets.symmetric(vertical: 40, horizontal: 30),
      decoration: BoxDecoration(
        color: getColorWhite1(szYjms: szUtilComm.szInfo.yjms),
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(30),
          topRight: Radius.circular(30),
        ),
      ),
      child: Column(
        children: [
          _titleItems(),
          hiSpace(height: 20),
          _textItem(),
        ],
      ),
    );
  }

  /// 输入框组件
  _textItem() {
    double fontSizeV = szUtilComm.szInfo.getZtdxPx()!;
    return TextField(
      controller: _textController,
      focusNode: _textFocusNode,
      // 设置光标颜色
      cursorColor: getColorBlue1(szYjms: szUtilComm.szInfo.yjms),
      // 光标高度
      cursorHeight: fontSizeV + 14,
      // 样式
      style: FontUtil.fontGrey2(fontSizeV),
      // 最多行数
      maxLines: 3,
      // 装饰
      decoration: InputDecoration(
        // 去掉textField自定的高度
        isCollapsed: true,
        // 提示语句
        hintText: "请输入笔记",
        // 提示语句样式
        hintStyle: FontUtil.fontGrey2(fontSizeV),
        // 内边距
        contentPadding: EdgeInsets.all(24),
        // 正常情况下的border边框
        border: InputBorder.none,
        // 输入框是否可用
        enabled: true,
      ),
    );
  }

  /// 标题组件显示
  _titleItems() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.end,
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        SizedBox(
          width: 100,
          child: _openItem(),
        ),
        _titleItem(),
        SizedBox(
          width: 100,
          child: _submitItem(),
        ),
      ],
    );
  }

  /// 是否公布组件
  _openItem() {
    Color color;
    bool yjms = szUtilComm.szInfo.yjms;
    if (_open) {
      color = getColorBlue1(szYjms: yjms);
    } else {
      color = getColorGrey11(szYjms: yjms);
    }
    return GestureDetector(
      onTap: () {
        setState(() {
          _open = !_open;
        });
      },
      child: Text(
        _open ? "公布" : "不公布",
        style: TextStyle(
          fontSize: 20,
          fontWeight: FontWeight.w400,
          color: color,
        ),
      ),
    );
  }

  /// 标题组件
  _titleItem() {
    return Text(
      "记笔记",
      style: FontUtil.fontBlack1(
        24,
        fontWeight: FontWeight.w500,
        szYjms: szUtilComm.szInfo.yjms,
      ),
    );
  }

  /// 提交组件
  _submitItem() {
    return GestureDetector(
      onTap: _onTapFunQd,
      child: Text(
        "提交",
        style: FontUtil.fontBlue1(
          20,
          szYjms: szUtilComm.szInfo.yjms,
        ),
        textAlign: TextAlign.end,
      ),
    );
  }

  /// 确定按钮点击方法
  void _onTapFunQd() {
    debugPrint(
        "nodeAddWidget 组件 -> 你点击了提交按钮 ===> ${widget.addType ? "试题提交" : "视频提交"}");
    String text = _textController.text;
    if (text.isEmpty) {
      ToastUtil.show(context: _context, msg: "请先输入笔记");
      return;
    }
    // 开启加载框
    ToastUtil.loadingBoxShow(_context);
    // 发起请求
    _futureAddNote(text: text).then((Map<String, dynamic> map) {
      // 关闭加载框
      ToastUtil.loadingBoxRemove();
      // 提示
      ToastUtil.show(context: _context, msg: map["msg"]);
      // 提交成功，则关闭提交组件
      if (map["suc"]) {
        Navigator.pop(_context);
      }
    });
  }

  // text：提交的笔记内容
  /// 提交笔记方法
  Future<Map<String, dynamic>> _futureAddNote({
    required String text,
  }) async {
    Map<String, dynamic> map = {};
    try {
      if (widget.addType) {
        // 试题提交笔记
        NoteModel model = _getNodeQuestion(text);
        await SubjectDao.noteUpdate(noteModel: model);
      } else {
        // 视频提交笔记
        NoteVideoModel model = _getNoteVideo(text);
        await CourseDao.noteUpdate(noteVideoModel: model);
      }
      map["suc"] = true;
      map["msg"] = "提交成功，请等待审核通过";
    } catch (e) {
      debugPrint("noteAddWidget 组件 -> 提交笔记发生异常 ===> $e");
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        debugPrint("noteAddWidget 组件 -> dao异常 ===> ${e.msg}");
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// 获取试题笔记对象
  NoteModel _getNodeQuestion(String text) {
    return NoteModel(
      open: _open,
      type: widget.type,
      relationId: widget.relationId,
      relationName: widget.relationName,
      content: text,
      verify: 0,
      questionId: widget.qId,
      categoryId: dataUtilComm.dataModel.categoryId.toString(),
      stem: widget.stem,
    );
  }

  /// 获取视频笔记对象
  NoteVideoModel _getNoteVideo(String text) {
    var userInfo = getUserInfo();
    // 是否需要自己上传用户信息
    return NoteVideoModel(
      open: _open,
      relationId: widget.relationId,
      relationName: widget.relationName,
      content: text,
      verify: 0,
      videoId: widget.videoId,
      categoryId: dataUtilComm.dataModel.categoryId.toString(),
      createName: userInfo.name,
      createHeader: userInfo.header,
    );
  }
}
